﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Web;
using Epona.AOP.Cache;

namespace Epona.Session
{
    public class Session
    {
        public const string SESSIONNAME = "__sessionname__";
        public string SessionId { get; set; }
        private HttpContextBase context;

        public Session(HttpContextBase context)
        {
            this.context = context;
            var cookie = context.Request.Cookies.Get(SESSIONNAME);
            if(cookie==null||string.IsNullOrEmpty(cookie.Value))
            {
                SessionId = Newid();
                context.Response.Cookies.Add(new HttpCookie(SESSIONNAME, SessionId));
                context.Request.Cookies.Add(new HttpCookie(SESSIONNAME, SessionId));
            }
            else
            {
                SessionId = cookie.Value;
            }
        }

        public object Get()
        {
            return new RedisCacheRepository().Get(SessionId);
        }

        public void Login(object o)
        {
            new RedisCacheRepository().Insert(SessionId,o,
                DateTime.Now.AddHours(Convert.ToDouble(ConfigurationManager.AppSettings["UserSessionTimeExpire"])) - DateTime.Now);
        }

        public void Logout()
        {
            new RedisCacheRepository().Delete(SessionId);
        }

        public bool Postpone()
        {
            return new RedisCacheRepository().ReSetExpire(SessionId,
                       DateTime.Now.AddHours(Convert.ToDouble(ConfigurationManager.AppSettings["UserSessionTimeExpire"])) - DateTime.Now);
        }

        private string Newid()
        {
            return SESSIONNAME + Guid.NewGuid().ToString();
        }
    }
}
